App.DataModel = Backbone.Model.extend({
	urlRoot : App.root + '/api/data'
});
App.DataCollection = Backbone.Collection.extend({
	model:    App.DataModel,
	urlRoot : App.root + '/api/data'
});

App.module('tableModule', function(tableModule){
	this.startWithParent = false;
	var _table = null;
   var MainView = Marionette.ItemView.extend({
		tagName: 'table',
	});
	var Controller = Marionette.Controller.extend({
		initialize: function(options){
			if (App.debug) console.log(this.moduleName + ' Controller initialized');
			this.options = options;
			this.data = new App.DataCollection;
			var self = this;
			$('.nbutton').on('click', function(e) {
				console.log($("#new-table").wijgrid('columns')[5])
				$("#new-table").wijgrid('columns')[5].options.filterOperator = 'equals';
				$("#new-table").wijgrid('columns')[5].options.filterValue = $(e.currentTarget).attr('rel');
				$("#new-table").wijgrid('ensureControl', true);
				console.log($(e.currentTarget).attr('index'));
				var index = $(e.currentTarget).attr('index')
				var context = $('[arial-level="1"]')[index];
				var title =  $('span', $('.wijmo-wijgrid-innercell', context)[0]).html();
				var title2 = $('div', $('.wijmo-wijgrid-innercell', context)[1]).html();
				console.log(title2);
				/*
				$('[arial-level="1"]').each(function(in, el){
					console.log($('.wijmo-wijgrid-innercell', $(el)))
				})
				*/
			});
			$('#radio').buttonset();	
		},
		refresh: function() {
			//$("#new-table").wijgrid("doRefresh");
		},
		click_test: function() {
			console.log('click_test');
		},
		show: function() {
			if (App.debug) console.log(self.moduleName + ' Controller show invoked');
			var main_view = new MainView({
				id: this.options.id,
				template: '#' + this.options.template,
			});
			this.options.region.show(main_view);
		},
		render: function() {
			if (App.debug) console.log(self.moduleName + ' Controller render invoked');
			$("#new-table").wijgrid({ 
            allowSorting: true,
				groupSingleRow: false,
				scrollMode: "auto",
				rendered : function (e) {
					App.vent.trigger('table:rendered');
					$('td', $('[arial-level="2"]')).css('font-weight', 'bold')
					$('td', $('[arial-level="2"]')).css('font-size', '16px')
					$('[arial-level="1"]').css('display',    'none')
					
					$('.graph').each(function(i, elem){
						var data1 = $(elem).attr('data1');
						var data2 = $(elem).attr('data2');
						$(elem).sparkline([data2, data1, 100], {type: 'bullet', width: '120px', height: '20px'});

					})
				},
				groupAggregate: function (e, args) {
					if (args.column.dataKey == "Avance") {
						var aggregate   = 0;
						var aggr_total  = 0;
						var aggr_avance = 0;
						var aggr_avance_esp = 0;
						for (var i = args.groupingStart; i <= args.groupingEnd; i++) {
							aggr_total  += parseFloat(args.data[i][7].value);
							aggr_avance += parseInt(args.data[i][8].value);
							aggr_avance_esp += parseFloat(args.data[i][9].value);
						}
						args.text = aggr_avance_esp*100/aggr_total;
						av_total = aggr_avance/aggr_total*100;
						av_esp   = aggr_avance_esp*100/aggr_total;
						if ((av_total - av_esp) > 10) {
								args.text = '<div class="red">' +  args.text.toFixed(2) + ' %</div>';
						}
						else if ((av_total - av_esp) > 5) {
								args.text = '<div class="orange">' +  args.text.toFixed(2) + ' %</div>';
						}
						else if ((av_total - av_esp) < -10) {
								args.text =  '<div class="blue">'  + args.text.toFixed(2) +  ' %</div>';
						}
						else if ((av_total - av_esp) < -5) {
							args.text = '<div class="black">' +  args.text.toFixed(2) + ' %</div>';
						}
						else  {
								args.text = '<div class="black">' +  args.text.toFixed(2) + ' %</div>';
						}
					}
					else if (args.column.dataKey == "Ttran") {
						var aggregate   = 0;
						var aggr_total  = 0;
						var aggr_avance = 0;
						for (var i = args.groupingStart; i <= args.groupingEnd; i++) {
							aggr_total  += parseInt(args.data[i][7].value);
							aggr_avance += parseInt(args.data[i][8].value);
						}
						args.text = (aggr_avance/aggr_total)*100;
						args.text = '<div class="bl">'  + args.text.toFixed(2)  +  ' %</div>';
					}
					else if (args.column.dataKey == "Finiciop") {
						var min = new Date(2999,12,31);

						for (var i = args.groupingStart; i <= args.groupingEnd; i++) {
							if ((args.data[i][3].value) < min) min = (args.data[i][3].value)
						}
						args.text = '<div class="bl">'  +  dateFormat(min, 'mmm-dd-yyyy');
					}
					else if (args.column.dataKey == "Ffinp") {
						var max = new Date(1970,1,1);

						for (var i = args.groupingStart; i <= args.groupingEnd; i++) {
							if ((args.data[i][4].value) > max) max = (args.data[i][4].value)
						}
						args.text = '<div class="bl">'  + dateFormat(max, 'mmm-dd-yyyy')+  '</div>';
					}
					else if (args.column.dataKey == "Dias") {
						sum = 0;
						min = 0;
						for (var i = args.groupingStart; i <= args.groupingEnd; i++) {
							if (args.data[i][10].value > 0) {
								sum += args.data[i][10].value
							}
							else {
								min += args.data[i][10].value
							}
						}
						
						args.text = '<div class="black">+'  + sum.toFixed(0) + ' / ' + min.toFixed(0)  +  '</div>';
					}
					
				},
            groupIndent: 10, 
            data: getData(200),
            columnsAutogenerationMode: "none", 
            columns: [ 
               { 
                  dataKey: "estrategico", 
                  headerText: "O. Estrategico", 
                  dataType: "string", 
                  visible: false,

                  groupInfo: { 
                     position: "header", 
                     //outlineMode: "startCollapsed", 
							headerText: "{0}"
                  }

               }, 
               { 
                  dataKey: "especifico", 
                  headerText: "O. Especifico", 
                  dataType: "string", 
                  visible: false,

                  groupInfo: { 
                     position: "header", 
                     //outlineMode: "startCollapsed", 
                     headerText: "{0}"
						}
               }, 
					{ dataKey: "Actividad", headerText: "Actividad", dataType: "string", textAlignment: "left"  },
					{ dataKey: "Finiciop", headerText:  "Inicio Programado", dataType: "datetime", dataFormatString: "MMM-dd-yyyy", textAlignment: "left", aggregate: 'custom'},
					{ dataKey: "Ffinp",    headerText:  "Fin Programado", dataType: "datetime", dataFormatString: "MMM-dd-yyyy", textAlignment: "left", aggregate: 'custom' }, 
					{ dataKey: "Ttran",    headerText:  "T. Transcurrido", dataType: "number", textAlignment: "left", aggregate: 'custom', dataFormatString: "p2" },
					{ 
                  dataKey: "Avance", 
                  headerText: "Avance", 
                  dataType: "number", 
                  visible: true,
						aggregate: 'custom',
						textAlignment: "left",
						dataFormatString: "p2",
						cellFormatter: function (args) {
							if (args.row.type & $.wijmo.wijgrid.rowType.data) { // data row (not group header) 
                        if ((args.row.data.Ttran - args.row.data.Avance) > .10) {             // discount > 25%? bold + red! 
                           args.$container.css("font-weight", "bold"); 
                              args.$container.css("color", "red");
                        }
                        else if ((args.row.data.Ttran - args.row.data.Avance) > .5) {             // discount > 25%? bold + red! 
                           args.$container.css("font-weight", "bold"); 
                              args.$container.css("color", "orange"); 
                        }
                        else if ((args.row.data.Ttran - args.row.data.Avance) < -.10) {             // discount > 25%? bold + red! 
                           args.$container.css("font-weight", "bold"); 
                              args.$container.css("color", "blue"); 
                        }
                        else {             // discount > 25%? bold + red! 
                           args.$container.css("font-weight", "bold"); 
                              args.$container.css("color", "black");
	                        }
                     }
                  } 
               },
					{ dataKey: "Diff", headerText: "Total Días", dataType: "number", textAlignment: "left", aggregate: 'sum', visible: false },	
					{ dataKey: "Avance_dias", headerText: "Avance Días", dataType: "number", textAlignment: "left", aggregate: 'sum', visible: false },
					{ dataKey: "Avance_esp", headerText: "Avance Esperado", dataType: "number", textAlignment: "left", aggregate: 'sum', visible: false },
					{ dataKey: "Dias", headerText: "Brecha (Días Favor/Contra)", dataType: "number", textAlignment: "left", aggregate: 'custom', visible: false },
               { 
                  dataKey: "text", 
                  headerText: "Text", 
                  dataType: "string", 
                  visible: true, 
					},
					{
						dataKey: 'graph',
						headerText: 'Graph',
						dataType: "string",
						visible: true,
					}
					
            ]}); 
			

			$('td', $('[arial-level="2"]')).css('font-weight', 'bold')
			$('td', $('[arial-level="2"]')).css('font-size', '16px')
			$('[arial-level="1"]').css('display',    'none')
			function getData(count) { 
            var data = []; 
            var country = "O. Estratégico 1,O. Estratégico 2,O. Estratégico 3,O. Estratégico 4,O. Estratégico 5".split(","); 
            var name = "O. Especifico 1 ,O. Especifico 2 ,O. Especifico 3 ,O. Especifico 4 ,O. Especifico 5 ".split(",");
				var act = "Actividad 1 ,Actividad 2 ,Actividad 3 ,Actividad 4 ,Actividad 5 ".split(",");
				
            for (var i = 0; i < count; i++) {
					rand_days1 = (Math.floor((Math.random()*300)));
					rand_days2 = (Math.floor((Math.random()*300)));
					date_ip  = getDate(rand_days1);
					date_fp  = getDate1(rand_days2);
					diff     = (date_fp - date_ip)/(1000*60*60*24);
					to_end   = (date_fp - new Date().getTime())/(1000*60*60*24);
					pto_end  = (to_end*100/diff)
					avance   = ((Math.random()*100) - (Math.random()*30)*(Math.random()) ).toFixed(2);
					if (avance < 10) {
						avance = ((Math.random()*10)).toFixed(2);
					}
					avance_dias = diff*(avance/100);
					ttran = ((new Date().getTime() - date_ip)/(1000*60*60*24))/diff;
					cc = getString(country)
					
					var data1 = avance
					//data1 = data1.toFixed(2);
					var data2 = ttran*100;
					data2 = data2.toFixed(2);
					
               data.push({ 
                  TransactionID: i, 
                  estrategico: cc, 
                  especifico: getString(name),
                  Actividad: getString(act),
						Finiciop: date_ip,
						Ffinp: date_fp,
						Ttran: ttran,
						Avance: avance/100,
						Diff: diff,
						Avance_dias: to_end,
						Avance_esp: (diff)*avance/100,
						Dias: diff*((avance-ttran*100)/100),
						text: cc,
						graph: '<div class="graph" data1="' + data1.toString() + '" data2="' + data2.toString() + '"></div>'
              }); 
            } 
            return data; 
			} 
			function getString(arr) { 
            return arr[Math.floor((Math.random() * arr.length))]; 
			} 
			function getNumber(lo, hi) { 
            return lo + Math.random() * (hi - lo); 
			} 
			function getDate(daysAgo) { 
            return new Date((new Date()).getTime() - (daysAgo) * 24 * 3600 * 1000);
			}
			function getDate1(daysAgo) { 
            return new Date((new Date()).getTime() + (daysAgo) * 24 * 3600 * 1000);
			}
		}
	});
	tableModule.addInitializer(function (options) {
		var defaults = {
         id:                         'new-table',
         template:                   'app-table-template'
		};
      options = _.extend(defaults, options);
		if (App.debug) console.log('App.dialogModule addInitializer invoked');
		tableModule.Controller = new Controller(options);
		tableModule.Controller.show();
		tableModule.Controller.render();
   });
});

App.tableModule.on("before:start", function(){
	if (App.debug) console.log(this.moduleName + ' before:start');
});

App.tableModule.on("start", function(){
	if (App.debug) console.log(this.moduleName + ' start');
});

